package com.woniuxy.service.impl;

import com.woniuxy.dao.ProductDao;
import com.woniuxy.entity.Product;
import com.woniuxy.service.ProductService;
import com.woniuxy.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Author: 曾令忠
 * @Description:
 * @Date: 2020/7/2 0002-下午 3:09
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    ProductDao productDao;

    private static final String namespace = "find";

    @Autowired
    private  RedisTemplate<String,Object> redisTemplate;

    @Override
    @Cacheable("all")
    public List<Product> getAll() {
        return productDao.getAll();
    }

    @Override
    @Cacheable("find")
    public Product findProductyId(int id) {
        return productDao.findProductyId(id);
    }

    @Override
//    @CacheEvict(value = {"all"},allEntries = true) //删除指定的key
    public int delById(int id) throws NoSuchMethodException {
        Method method = this.getClass().getDeclaredMethod("findProductyId",new Class[]{int.class});
        String key = RedisUtil.generate(namespace,this,method,id);
        System.out.println(key);
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        redisTemplate.delete(key);
        return productDao.delById(id);
    }


}
